package com.frt.sygang.sevice.impl;/**
 * Created by 冯瑞涛 on 2022/9/22 10:34
 */

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.frt.sygang.entity.ShoppingCart;
import com.frt.sygang.mapper.ShoppingCartMapper;
import com.frt.sygang.sevice.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 冯瑞涛
 * @version 1.0
 * @date 2022/9/22 10:34
 */
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    @Transactional
    public void subShopping(Long dishId, Long setmealId, HttpServletRequest request) {
        Long userId = (Long) request.getSession().getAttribute("user");
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        wrapper.eq(setmealId != null, ShoppingCart::getSetmealId, setmealId);
        wrapper.eq(dishId != null, ShoppingCart::getDishId, dishId);
        ShoppingCart shoppingCart = this.getOne(wrapper);
        Integer number = shoppingCart.getNumber();
        LambdaUpdateWrapper<ShoppingCart> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ShoppingCart::getUserId, userId);
        updateWrapper.eq(setmealId != null, ShoppingCart::getSetmealId, setmealId);
        updateWrapper.eq(dishId!= null, ShoppingCart::getDishId, dishId);
        if (number > 1) {
            updateWrapper.set(ShoppingCart::getNumber, number - 1);
            this.update(updateWrapper);
        } else {
            this.remove(updateWrapper);
        }
    }
}
